//
//  OrderDetailViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/2.
//  Copyright © 2018年 四川中农. All rights reserved.
//


enum OrderStatus:Int {
    case waitPay = 0 // 待支付
    case waitDelivery = 2 // 待收货
    case done = 3  // 已完成
    case cancel = 4 // 已取消
}

import UIKit

class OrderDetailViewController: BaseViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var tblHeader:OrderDetailheader!
    
    @IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
    var orderModel : OrderListModel!
    
    @IBOutlet weak var confirmButton: UIButton!
    @IBOutlet weak var cancelButton: UIButton!
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        
        view.backClosure = { [weak self] in
            self?.orderUpate()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "订单详情"
        self.tblHeader = OrderDetailheader.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 0), model:self.orderModel)
        self.tableView.backgroundColor = UIColor.backgroundColor
        self.tableView.tableHeaderView = self.tblHeader
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 10))
        footer.backgroundColor = UIColor.backgroundColor
        self.tableView.tableFooterView = footer
        
        self.confirmButton.setCornerRadio(radio: 15, isMask: false)
        self.confirmButton.setShadow(color: "#f7c201", offset: CGSize.init(width: 0, height: 4), radius: 8, opacity: 0.2)
        
        self.cancelButton.setBorder(color: "#f7c201", width: 1)
        self.cancelButton.setCornerRadio(radio: 15, isMask: false)
        
        updateBottomViewBtn()
    }
    
    func updateBottomViewBtn(){
        switch self.orderModel.state {
        case 0:
            // 订单类型 0立即支付 1货到付款
            if orderModel.type == 0 {
                self.cancelButton.setTitle("取消订单", for: .normal)
                self.confirmButton.setTitle("确认付款", for: .normal)
            }else{
                self.cancelButton.isHidden = true
                self.confirmButton.setTitle("确认付款", for: .normal)
            }
        case 1,2:
            
            self.cancelButton.isHidden = true
            if orderModel.state == 2 {
                self.confirmButton.setTitle("确认收货", for: .normal)
            }else{
                if orderModel.type == 0 {
                    self.confirmButton.isHidden = true
                    self.bottomViewHeight.constant = 0
                }else{
                    self.confirmButton.isHidden = false
                    self.confirmButton.setTitle("取消订单", for: .normal)
                }
            }
        case 3:
            self.cancelButton.isHidden = true
            self.confirmButton.setTitle("再来一单", for: .normal)
        case 4:
            self.cancelButton.isHidden = true
            self.confirmButton.setTitle("再来一单", for: .normal)
        default:
            break
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK:取消订单
    @IBAction func cancelButtonClick(_ sender: UIButton) {
        self.checkBtnClick(sender: sender)
    }
    
    
    // MARK:确认付款
    @IBAction func confirmbuttonClick(_ sender: UIButton) {
        self.checkBtnClick(sender: sender)
    }
    
    func checkBtnClick(sender:UIButton){
        switch sender.titleLabel?.text! {
        case "取消订单","确认收货":
            var title = "确定要收货吗？"
            if sender.titleLabel?.text != "确认收货" {
                title = "确定要取消订单吗？"
            }
            self.alertView.show(withTitle: title)
            
        case "再来一单":
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ShoppingCartViewController") as! ShoppingCartViewController
            ctrl.orderId = self.orderModel.id
            self.navigationController?.pushViewController(ctrl, animated: true)
            
            
        case "确认付款":
            var model = ConfirmOrderModel()
            model.money = self.orderModel.money
            
            var arr = [OrdersModel]()
            var orderMdl =  OrdersModel()
            orderMdl.number = self.orderModel.number
            orderMdl.money = self.orderModel.money
            orderMdl.id = self.orderModel.id
            arr.append(orderMdl)
            model.orders = arr
            
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SelePayViewController") as! SelePayViewController
            ctrl.model = model
            self.navigationController?.pushViewController(ctrl, animated: true)
        default:
            break
        }
    }
    
    func orderUpate(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.orderUpdate.rawValue, parameters: ["id":self.orderModel.id]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "操作成功!")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateList"), object: nil)
                Utils.DispatchAfter(after: 0.5, handler: {
                    self.backBarButtonMethon()
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    

}

extension OrderDetailViewController:UITableViewDelegate,UITableViewDataSource {
  
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3 + (self.orderModel.remarks == "" ? 0 : 1)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? self.orderModel.goods!.count : 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderDetailGoodsTableViewCell") as! OrderDetailGoodsTableViewCell
            cell.reload(withModel: self.orderModel.goods![indexPath.row])
            if indexPath.row == self.orderModel.goods!.count - 1 {
                cell.viewLine.isHidden = true
            }
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderPriceTableViewCell") as! OrderPriceTableViewCell
            let price = Double.init(self.orderModel.money)
            let coupon = self.orderModel.couponMoney == "" ? 0 : Double.init(self.orderModel.couponMoney)
            cell.reload(withGoodsPrice: self.orderModel.money, couponMoney: self.orderModel.couponMoney == "" ? "0.00" : self.orderModel.couponMoney, freight: "0.00", total: "\(price! + coupon!)")
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderDetailTableViewCell") as! OrderDetailTableViewCell
            cell.reload(withModel: self.orderModel)
            return cell
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: "RemarkTableViewCell") as! RemarkTableViewCell
            cell.remarkLabel.text = self.orderModel.remarks
            return cell
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return 100
        case 1:
            return 145
        case 2:
            return 165
        case 3:
            self.tableView.rowHeight = UITableViewAutomaticDimension
            self.tableView.estimatedRowHeight = 67
            return self.tableView.rowHeight
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 28
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 10, width: UIScreen.ScreenWidth, height: 28))
            header.backgroundColor = UIColor.white
            let titleLabel = Utils.labelWith(frame: CGRect.init(x: 12, y: 28 - 13.5, width:header.width , height: 13.5), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: .left, textColor: "#000000", text: "包裹清单（共\(self.orderModel.goods!.count)种）")
            header.addSubview(titleLabel)
            return header
        }
        return UIView.init()
    }
}






















